package main;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;

import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;


public class ConvertPDF {

	public static void main(String args[]) {
		if (args.length!=2) {   
			usage();	//Show usage and die
		}
		
		System.out.println(" Input file: " + args[0]);
		System.out.println("Output file: " + args[1]);

		if (!new File(args[0]).exists()) {
			System.err.println("Input file, " + args[0] + " does not exist.");
			System.exit(1);
		} else {
			System.out.println("Process Input file...");
		}
		
	    PDFParser parser = null;
	    PDDocument pdDoc = null;
	    COSDocument cosDoc = null;
	    PDFTextStripper pdfStripper;

	    String parsedText;
	    String fileName = args[0];
	    File file = new File(fileName);
		File outputFile = new File(args[1]);
		FileWriter output = null;
		
	    try {
	    	String outputPath = outputFile.getParent();
	    	if (!(new File(outputPath).isDirectory())) {
	    		new File(outputPath).mkdir();
	    	}
			output = new FileWriter(outputFile);
	        parser = new PDFParser(new FileInputStream(file));
	        parser.parse();
	        cosDoc = parser.getDocument();
	        pdfStripper = new PDFTextStripper();
	        pdDoc = new PDDocument(cosDoc);
	        parsedText = pdfStripper.getText(pdDoc);
			//Write to Load File
			output.write(parsedText.replaceAll("[^A-Za-z0-9. \n]+", ""));
//			output.write(parsedText.replaceAll("(  )+", ","));
			output.flush();	        
	    } catch (Exception e) {
	        e.printStackTrace();
	        try {
	            if (cosDoc != null)
	                cosDoc.close();
	            if (pdDoc != null)
	                pdDoc.close();
	        } catch (Exception e1) {
	            e.printStackTrace();
	        }
	    }
	    
	    System.out.println("Complete!");
	}

	private static void usage() {
		System.err.println("Usage - convertPDF InputFile OutputFile");
		System.exit(1);
	}
}
